package com.yeepay.bc.app.ut;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.crypto.Cipher;

import com.yeepay.bc.app.ut.Base64;
import com.yeepay.bc.app.ut.RSAEncryptCoder;

public class RSAEncryptCoder {
	/**
	 * 加密方法名
	 */
	public static final String KEY_ALGORITHM = "RSA";

	public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";

	/**
	 * Map的Key常量
	 */
	private static String PUBLIC_KEY = "RSAPublicKey";
	private static String PRIVATE_KEY = "RSAPrivateKey";
	
	/**
	 * 用私钥对信息生成数字签名
	 * 
	 * @param data 加密数据
	 * @param privateKey 私钥
	 * @return 加密后字符串
	 * @throws Exception
	 */
	public static String sign(String privateKey, String content, String charset) throws Exception{
		// 解密由base64编码的私钥
		byte[] keyBytes = Base64.decode(privateKey);
		
		// 构造PKCS8EncodedKeySpec对象
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(keyBytes);
		
		// KEY_ALGORITHM 指定的加密算法
		KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
		
		// 取私钥匙对象
		PrivateKey myPriKey = factory.generatePrivate(priPKCS8);
		
		// 用私钥对信息生成数字签名
		Signature signet = Signature.getInstance(SIGNATURE_ALGORITHM);
		signet.initSign(myPriKey);
		signet.update(content.getBytes(charset));
		
		return Base64.encode( signet.sign());
	}

	/**
	 * 校验数字签名
	 * 
	 * @param data 加密数据
	 * @param publicKey 公钥
	 * @param sign 数字签名
	 * @return 校验成功返回true 失败返回false
	 * @throws Exception
	 */
	public static boolean verify(String sign, String publicKey, String content, String charset) throws Exception {
		// 解密由base64编码的公钥
		byte[] keyBytes = Base64.decode(publicKey);
		
		// 构造X509EncodedKeySpec对象
		X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(keyBytes);
		
		// KEY_ALGORITHM 指定的加密算法
		KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
		
		// 取公钥匙对象
		PublicKey pubKey = factory.generatePublic(bobPubKeySpec);
		
		// 用公钥解密签名信息
		Signature signetcheck = Signature.getInstance(SIGNATURE_ALGORITHM);
		signetcheck.initVerify(pubKey);
		signetcheck.update(content.getBytes(charset));
		
		return signetcheck.verify(Base64.decode(sign) );
	}

	/**
	 * 解密<br>
	 * 用私钥解密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception
	{
		// 对密钥解密
		byte[] keyBytes = Base64.decode(key);

		// 取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

		// 对数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateKey);

		return cipher.doFinal(data);
	}

	/**
	 * 解密<br>
	 * 用公钥解密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception
	{
		// 对密钥解密
		byte[] keyBytes = Base64.decode(key);
		// 取得公钥
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicKey = keyFactory.generatePublic(x509KeySpec);

		// 对数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, publicKey);

		return cipher.doFinal(data);
	}

	/**
	 * 加密<br>
	 * 用公钥加密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception
	{
		// 对公钥解密
		byte[] keyBytes = Base64.decode(key);

		// 取得公钥
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicKey = keyFactory.generatePublic(x509KeySpec);

		// 对数据加密
		//Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);

		return cipher.doFinal(data);
	}
	
	/**
	* 解密
	* @param content 密文
	* @param private_key 商户私钥
	* @param input_charset 编码格式
	* @return 解密后的字符串
	 * @throws Exception 
	*/
	public static String decryptByPrivateKey(String content, String privateKey, String inputCharset) throws Exception {
		PrivateKey prikey = getPrivateKey(privateKey);

		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, prikey);

		InputStream ins = new ByteArrayInputStream(Base64.decode(content));
		ByteArrayOutputStream writer = new ByteArrayOutputStream();
		// rsa解密的字节大小最多是128，将需要解密的内容，按128位拆开解密
		byte[] buf = new byte[128];
		int bufl;

		while ((bufl = ins.read(buf)) != -1) {
			byte[] block = null;
			if (buf.length == bufl) {
				block = buf;
			} else {
				block = new byte[bufl];
				for (int i = 0; i < bufl; i++) {
					block[i] = buf[i];
				}
			}
			writer.write(cipher.doFinal(block));
		}
		return new String(writer.toByteArray(), inputCharset);
	}
	
	/**
	 * 加密<br>
	 * 用私钥加密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptByPrivateKey(byte[] data, String key) throws Exception
	{
		// 对密钥解密
		byte[] keyBytes = Base64.decode(key);

		// 取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);

		return cipher.doFinal(data);
	}

	/**
	 * 取得私钥
	 * 
	 * @param keyMap
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
    public static String getPrivateKey(Map keyMap) throws Exception
	{
		Key key = (Key) keyMap.get(PRIVATE_KEY);
		return Base64.encode(key.getEncoded());
	}
	
	/**
	* 得到私钥
	* @param key 密钥字符串（经过base64编码）
	* @throws Exception
	*/
	public static PrivateKey getPrivateKey(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = Base64.decode(key);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
		return privateKey;
	}
	
	/**
	 * 取得公钥
	 * 
	 * @param keyMap
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
    public static String getPublicKey(Map keyMap) throws Exception
	{
		Key key = (Key) keyMap.get(PUBLIC_KEY);
		return Base64.encode(key.getEncoded());
	}

	/**
	 * 生成密钥密钥
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Map<String,Object> generateKey(String seed) throws Exception {
		KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		
		SecureRandom secrand = new SecureRandom();
		secrand.setSeed(seed.getBytes()); // 随机产生器
		keygen.initialize(1024, secrand);
		
		KeyPair keys = keygen.genKeyPair();
		
		PublicKey publicKey  = keys.getPublic();
		PrivateKey privateKey = keys.getPrivate();
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put(PUBLIC_KEY, publicKey);
		map.put(PRIVATE_KEY, privateKey);
		
		return map;
	}
	
	public static String getPublicKeyByCert(String certPath){
        String publicKeyStr="";
        FileInputStream in =null;
	    try {
//	    	if(StringUtils.isBlank(certPath)) {
//		      return null;
//			}
	    	if(null==certPath || "".equals(certPath)){
			      return null;
	    	}
	    	CertificateFactory cf = CertificateFactory.getInstance("X.509");
	    	in  = new FileInputStream(certPath);
	        X509Certificate publicCert = (X509Certificate)cf.generateCertificate(in);
	        publicKeyStr=Base64.encode(publicCert.getPublicKey().getEncoded());
	    }catch (CertificateException e) {
	        close(in);
	    }catch (FileNotFoundException e1){
	        close(in);
	    }finally{
	    	close(in);
	    }
	    return publicKeyStr;
	 }

	@SuppressWarnings("rawtypes")
	public static String getPrivateKeyByCert(String certPath,String password){
	      String privateKeyStr="";
	      FileInputStream fis=null;
	      try{
    	    KeyStore  keyStore = KeyStore.getInstance("PKCS12");
	        fis = new FileInputStream(certPath);
	        char[] nPassword = (char[])null;
	        nPassword = (password == null) || ("".equals(password.trim())) ? null : password.toCharArray();
	        if (keyStore != null) {
	        	keyStore.load(fis, nPassword);
	        } 
	        Enumeration aliasenum = keyStore.aliases();
	        String keyAlias = null;
	        if (aliasenum.hasMoreElements()) {
	          keyAlias = (String)aliasenum.nextElement();
	        }
	        PrivateKey privateKey=(PrivateKey)keyStore.getKey(keyAlias,password.toCharArray());
	        privateKeyStr= Base64.encode(privateKey.getEncoded());
	      }catch(FileNotFoundException e1){
		      close(fis);
	      }catch (CertificateException e) {
	          close(fis); 
		  }catch (NoSuchAlgorithmException e2) {
	          close(fis);
		  }catch (KeyStoreException e3) {
	          close(fis);
		  }catch (IOException e4) {
	          close(fis);
		  }catch (UnrecoverableKeyException e4) {
	          close(fis);
		  }finally{
			  close(fis);
		  }
         return privateKeyStr;
	}
	
	/**
	 * 公钥加密
	 * 
	 *  @param content
	 *           明文@param publicKey
	 *           服务器公钥
	 *                
	 * @return 加密后的字符串
	 */
	public static String encrypt(String content, String key)  {
		    Cipher cipher=null;
		    ByteArrayOutputStream writer=null; 
		    try{
		    	// 对公钥解密
				byte[] keyBytes = Base64.decode(key);
				// 取得公钥
				X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
				KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
				Key publicKey = keyFactory.generatePublic(x509KeySpec);

				cipher= Cipher.getInstance("RSA");
				cipher.init(Cipher.ENCRYPT_MODE, publicKey);
				content = java.net.URLEncoder.encode(content, "utf-8");
				InputStream ins = new ByteArrayInputStream(content.getBytes());
				writer= new ByteArrayOutputStream();
				// rsa解密的字节大小最多是100，将需要解密的内容，按100位拆开解密
				byte[] buf = new byte[100];
				int bufl;
				while ((bufl = ins.read(buf)) != -1) {
					byte[] block = null;
					if (buf.length == bufl) {
						block = buf;
					} else {
						block = new byte[bufl];
						for (int i = 0; i < bufl; i++) {
							block[i] = buf[i];
						}
					}
					writer.write(cipher.doFinal(block));
				}
		    }catch(Exception e){
		    	e.printStackTrace();
		    }
		   return Base64.encode(writer.toByteArray());
	}
	
	public static void close(FileInputStream in){
		if(in != null)
		  try{
			  in.close();
		  }catch(IOException e1){
		  }
	}
	
	/**
	 * 测试生成
	 * @throws Exception
	 */
	@SuppressWarnings({"rawtypes", "unused"})
	public static void main(String[]args) throws Exception{
		String seed = "381" + UUID.randomUUID().toString() ;
		Map map = RSAEncryptCoder.generateKey(seed);

/*		System.out.println("RSA加密种子："+seed);
		System.out.println();
		System.out.println("公钥："+ RSAEncryptCoder.getPublicKey(map));
		System.out.println();
		System.out.println("私钥："+ RSAEncryptCoder.getPrivateKey(map));
		*/
		String signData=sign("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMtsdEKIVRfu+bgIPp8UulBVxYWH8fqVfEoF3XhvSBakE9fL7nl0IShRv6Q/jiR6yKke0DRz51owurUhiqIpKDBuPWws8zFYr8SbILJtqk2eyVZHhnxB5QX8mztrRFrr/4oOXvf+Hqj9RA0cT1i50A35SV/WG5DzIGhblvvx5B0JAgMBAAECgYA/kNlXfQCSJQP1hOYEkdaSieraChwMQLAA9Yo6OxPct1LYCQqw+x/tWHY5Hf8N2Sxg5JcM/PbbUQTW2u9WMuQyh3C60T5JEZZbjkHNpYwk+s9GagvjIx6FHXz8hHnDjNP3/pJH5w2ZjGVAzRq1I7JHYDM+wElvzWkco1j3Az/abQJBAOXGxbZlHU3qQk/Gng4bYEUppNvHhMb4+/0s+0KkP8MJQwvVaHMB2T2Q7O0IiSaz17fI2xRyVL3djbGHEBQaaU8CQQDio7/NW6JpwiHLYO5d9fnAU1yM2zc+5fxfO+xPsuTplwZjM3zzaU7Hs9xdSPU4sCSsjKt217LnO8DR3n1LuE4nAkBqD811eskDDQ3c2xZb9qECa82QMVGFsqpGW/wC7+QKt/y9up1C8OiA9aOXaig8uCjryYfusTOSjHD6MBjo3qQbAkBNC4udfSQ2PaeNYvNFf+QaTHxu6era+AYWPeG0qkUFX7DtMkis2sTMQMmN8MpkLgUZn2x+pw8LapW/Apqnjg0LAkEAmmJgXIS159fDs7dzCEMQZr/sOxZlHQ81xYQLoAt7elBjEecWn+xBJLIFsYxNsw6P/oVQ7ipXrQEpYxANZe/c4w==","这是一个测试","UTF-8");
	    System.out.println("签名"+signData);
	    boolean flag=verify(signData,"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLbHRCiFUX7vm4CD6fFLpQVcWFh/H6lXxKBd14b0gWpBPXy+55dCEoUb+kP44kesipHtA0c+daMLq1IYqiKSgwbj1sLPMxWK/EmyCybapNnslWR4Z8QeUF/Js7a0Ra6/+KDl73/h6o/UQNHE9YudAN+Ulf1huQ8yBoW5b78eQdCQIDAQAB","这是一个测试","UTF-8");
	    System.out.println("签名验证结果："+flag);
	    byte[] enData=encryptByPublicKey("这是个测试".getBytes("UTF-8"),"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLbHRCiFUX7vm4CD6fFLpQVcWFh/H6lXxKBd14b0gWpBPXy+55dCEoUb+kP44kesipHtA0c+daMLq1IYqiKSgwbj1sLPMxWK/EmyCybapNnslWR4Z8QeUF/Js7a0Ra6/+KDl73/h6o/UQNHE9YudAN+Ulf1huQ8yBoW5b78eQdCQIDAQAB");
	    System.out.println(Base64.encode(enData));
	    byte[] data=decryptByPrivateKey(enData, "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMtsdEKIVRfu+bgIPp8UulBVxYWH8fqVfEoF3XhvSBakE9fL7nl0IShRv6Q/jiR6yKke0DRz51owurUhiqIpKDBuPWws8zFYr8SbILJtqk2eyVZHhnxB5QX8mztrRFrr/4oOXvf+Hqj9RA0cT1i50A35SV/WG5DzIGhblvvx5B0JAgMBAAECgYA/kNlXfQCSJQP1hOYEkdaSieraChwMQLAA9Yo6OxPct1LYCQqw+x/tWHY5Hf8N2Sxg5JcM/PbbUQTW2u9WMuQyh3C60T5JEZZbjkHNpYwk+s9GagvjIx6FHXz8hHnDjNP3/pJH5w2ZjGVAzRq1I7JHYDM+wElvzWkco1j3Az/abQJBAOXGxbZlHU3qQk/Gng4bYEUppNvHhMb4+/0s+0KkP8MJQwvVaHMB2T2Q7O0IiSaz17fI2xRyVL3djbGHEBQaaU8CQQDio7/NW6JpwiHLYO5d9fnAU1yM2zc+5fxfO+xPsuTplwZjM3zzaU7Hs9xdSPU4sCSsjKt217LnO8DR3n1LuE4nAkBqD811eskDDQ3c2xZb9qECa82QMVGFsqpGW/wC7+QKt/y9up1C8OiA9aOXaig8uCjryYfusTOSjHD6MBjo3qQbAkBNC4udfSQ2PaeNYvNFf+QaTHxu6era+AYWPeG0qkUFX7DtMkis2sTMQMmN8MpkLgUZn2x+pw8LapW/Apqnjg0LAkEAmmJgXIS159fDs7dzCEMQZr/sOxZlHQ81xYQLoAt7elBjEecWn+xBJLIFsYxNsw6P/oVQ7ipXrQEpYxANZe/c4w==");
        System.out.println(new String(data,"UTF-8"));
	}

}
